package com.zrrd.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zrrd.reggie.bean.ShoppingCart;
import com.zrrd.reggie.common.BaseContext;
import com.zrrd.reggie.common.R;
import com.zrrd.reggie.service.ShoppingCartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("shoppingCart")
public class ShoppingCartController {

    @Autowired
    private ShoppingCartService shoppingCartService;

    @PostMapping("add")
    public R<ShoppingCart> add(@RequestBody ShoppingCart shoppingCart){
        ShoppingCart addcart = shoppingCartService.addcart(shoppingCart);
        return  R.sucess(addcart);
    }

    @GetMapping("list")
    public R<List> list(){
        QueryWrapper<ShoppingCart> wrapper=new QueryWrapper<>();
        wrapper.eq("user_id", BaseContext.getCurrentId());
        wrapper.orderByDesc("create_time");
        return R.sucess(shoppingCartService.list(wrapper));
    }

    @DeleteMapping("clean")
    public R<String> clean(){
        QueryWrapper<ShoppingCart> wrapper=new QueryWrapper<>();
        wrapper.eq("user_id",BaseContext.getCurrentId());
        return shoppingCartService.remove(wrapper)?R.sucess("删除成功"):R.error("删除失败");
    }

    @PostMapping("sub")
    public R<ShoppingCart> sub(@RequestBody ShoppingCart shoppingCart){
        QueryWrapper<ShoppingCart> wrapper=new QueryWrapper<>();
        wrapper.eq("user_id", BaseContext.getCurrentId());
        Long dishId = shoppingCart.getDishId();
        if (dishId!=null){
            wrapper.eq("dish_id",dishId);
        }else {
            wrapper.eq("setmeal_id",shoppingCart.getSetmealId());
        }
        ShoppingCart cart = shoppingCartService.getOne(wrapper);
        cart.setNumber(cart.getNumber()-1);
        shoppingCartService.updateById(cart);
        if (cart.getNumber()<=0){
            shoppingCartService.remove(wrapper);
        }
        return R.sucess(cart);
    }
}

